// 创建右键菜单
chrome.runtime.onInstalled.addListener(() => {
  chrome.contextMenus.create({
    id: 'html-to-markdown',
    title: '转换为 Markdown',
    contexts: ['selection']
  });
});

// 处理右键菜单点击事件
chrome.contextMenus.onClicked.addListener((info, tab) => {
  if (info.menuItemId === 'html-to-markdown') {
    // 向content script发送消息
    chrome.tabs.sendMessage(tab.id, {
      action: 'convertToMarkdown',
      selectionText: info.selectionText
    });
  }
});

// 监听来自content script的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'showMarkdown') {
    // 创建新标签页显示转换结果
    chrome.tabs.create({
      url: chrome.runtime.getURL('result.html')
    }, (tab) => {
      // 等待页面加载完成后发送数据
      chrome.tabs.onUpdated.addListener(function listener(tabId, info) {
        if (tabId === tab.id && info.status === 'complete') {
          chrome.tabs.onUpdated.removeListener(listener);
          chrome.tabs.sendMessage(tab.id, {
            action: 'displayResult',
            markdown: request.markdown,
            originalHtml: request.originalHtml
          });
        }
      });
    });
  } else if (request.action === 'copyToClipboard') {
    // 直接复制到剪贴板并显示通知
    chrome.tabs.sendMessage(sender.tab.id, {
      action: 'copyMarkdownToClipboard',
      markdown: request.markdown
    });
  }
});